package com.zhuhjay.domain.http;

import com.fasterxml.jackson.annotation.JsonInclude;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhuHJay
 * @date 2023/1/5 20:17
 */
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Result extends HashMap<String, Object> {
    /** 定义集合中`key`的标签 **/
    private static final String STATUS_TAG = "code";
    private static final String MESSAGE_TAG = "message";
    private static final String DATA_TAG = "result";
    /** 用来存放数据的集合 **/
    private final Map<String, Object> dataMap = new HashMap<>();

    private Result(int code, String message){
        super.put(STATUS_TAG, code);
        super.put(MESSAGE_TAG, message);
        super.put(DATA_TAG, dataMap);
    }

    private static Result createResult(HttpCode code, String message) {
        return new Result(code.getCode(), message);
    }

    public static Result ok(HttpCode code, String message) {
        return createResult(code, message);
    }

    public static Result ok(String message){
        return createResult(HttpCode.SUCCESS, message);
    }

    public static Result ok(){
        return Result.ok("操作成功");
    }

    public static Result fail(HttpCode code, String message) {
        return createResult(code, message);
    }

    public static Result fail(String message){
        return createResult(HttpCode.USER_ERROR, message);
    }

    public static Result fail(){
        return fail(HttpCode.USER_ERROR.getDesc());
    }

    public Result data(String key, Object value){
        dataMap.put(key, value);
        return this;
    }

    public Result beanToData(Object o) {
        Class<?> clazz = o.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object value = field.get(o);
                dataMap.put(field.getName(), value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return this;
    }
}
